﻿using Haidou.Wpf.UI;
using Haidou.Wpf.UI.Windows.Composer;
using Haidou.Wpf.Util;
using Haidou.Wpf.Util.Settings; // 引入主窗口命名空间
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Haidou.Wpf.UI.Windows.Other
{
    /// <summary>
    /// Startup.xaml 的交互逻辑
    /// </summary>
    public partial class Startup : Window
    {
        public StartupViewModel ViewModel { get; }
        public Startup()
        {
            InitializeComponent();
            DataContext = ViewModel = new StartupViewModel();
            _ = ViewModel.RunAsync(OnFinishAsync);
        }

        private async Task OnFinishAsync()
        {
			TodoCalendarWindow todoCalendarWindow  = new TodoCalendarWindow();
            todoCalendarWindow.Show();
			//var mainWindow = new MainWindow();
   //         mainWindow.Show();

            await Task.Delay(100); // 轻缓冲
            Close();

        }

        private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ButtonState == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void NI_Icon_MouseDoubleClick(object sender, RoutedEventArgs e)
        {
            NI_Icon.CloseContextControl();
        }

        private void NI_Icon_Click(object sender, RoutedEventArgs e)
        {
            NI_Icon.CloseContextControl();
        }

        private void NI_Icon_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
        }

        private void OpenMainWindowButton_Click(object sender, RoutedEventArgs e)
        {
            NI_Icon.CloseContextControl();
        }

        private void SettingsButton_Click(object sender, RoutedEventArgs e)
        {
            App.MainViewModel.OpenOptions.Execute(0);
            NI_Icon.CloseContextControl();
        }

        private void CheckUpdateButton_Click(object sender, RoutedEventArgs e)
        {
            // TODO: 调用更新检测逻辑
            NI_Icon.CloseContextControl();
        }

        private void FeedbackButton_Click(object sender, RoutedEventArgs e)
        {
            // TODO: 打开反馈窗口或链接
            NI_Icon.CloseContextControl();
        }

        private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                NI_Icon.CloseContextControl();
                NI_Icon.Dispose();

                try
                {
                    ThreadExitis("TikTokData");
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex.Message);
                }

                System.Windows.Application.Current.Shutdown(69);
            }
            catch (Exception ex)
            {
                LogWriter.Log("APP 退出 exitMitem_PreviewMouseDown" + ex.Message);
            }
        }

        public bool ThreadExitis(string threadName)
        {
            Process[] processList = Process.GetProcesses();
            List<Process> killList = new List<Process>();

            foreach (Process process in processList)
            {
                try
                {
                    if (process.ProcessName.Contains(threadName))
                    {
                        if (!IsCriticalProcess(process))
                        {
                            killList.Add(process);
                        }
                        else
                        {
                            Console.WriteLine($"跳过终止关键进程: {process.ProcessName}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"无法访问进程 {process.ProcessName}: {ex.Message}");
                }
            }

            foreach (Process process in killList)
            {
                process.Kill();
                Console.WriteLine($"已终止进程: {process.ProcessName}");
            }

            return killList.Any();
        }

        private bool IsCriticalProcess(Process process) => IsCurrentRunningAIHub(process);

        private bool IsCurrentRunningAIHub(Process process) => process.Id == GetCurrentAIHubProcessId();

        private int GetCurrentAIHubProcessId() => UserSettings.All.CurrentProcessId; // 示例值
    }

    public class StartupViewModel : INotifyPropertyChanged
    {
        private const int TotalDurationMs = 1600;          // 总加载时长 1.6s
        private const int ProgressSteps = 100;             // 平滑进度步数
        private const string LoadingText = "资源加载中...";

        public int TotalChecks => ProgressSteps;

        private int _completedCount;
        public int CompletedCount
        {
            get => _completedCount;
            set
            {
                if (_completedCount == value) return;
                _completedCount = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(ProgressText));
            }
        }

        private string _currentMessage = LoadingText;
        public string CurrentMessage
        {
            get => _currentMessage;
            private set { if (_currentMessage != value) { _currentMessage = value; OnPropertyChanged(); } }
        }

        public string ProgressText => CompletedCount >= TotalChecks ? "已完成" : $"{CompletedCount * 100 / TotalChecks}%";

        public async Task RunAsync(Func<Task>? onFinish = null)
        {
            CurrentMessage = LoadingText;
            int interval = TotalDurationMs / ProgressSteps;
            for (int i = 1; i <= ProgressSteps; i++)
            {
                await Task.Delay(interval);
                CompletedCount = i;
            }
            CurrentMessage = "加载完成";
            if (onFinish != null)
                await onFinish();
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}
